<?php
namespace Swostar\Event;

use Exception;

/**
 * 事件类
 * @package Swostar\Event
 */
class Event
{
    protected $events = [];

    /**
     * 事件注册
     * @param string $event 事件标识
     * @param Callback $callback 闭包
     * @return void 
     */
    public function register(string $event, $callback)
    {
        $event = strtolower($event);

        $this->events[$event] = ['callback' => $callback];
    }

    /**
     * 事件触发
     * @param string $event 事件标识
     * @param array $params 参数
     * @return true 
     * @throws Exception 
     */
    public function trigger(string $event, $params = [])
    {
        $event = strtolower($event);

        if (isset($this->events[$event])) {
            ($this->events[$event]['callback'])(...$params);
            return true;
        }

        throw new Exception('事件不存在', 500);
    }

    /**
     * 获取事件
     * @param mixed|null $event 事件标识
     * @return array|mixed 对应事件或全部事件数组
     */
    public function getEvents($event = null)
    {
        return empty($event) ? $this->events : $this->events[$event];
    }

    /**
     * 判断是否有事件注册
     * @param string $event 
     * @return bool 
     */
    public function has(string $event)
    {
        return isset($this->events[$event]);
    }

}